import {
	defineStore
} from 'pinia'
import {
	exchangeCodeForOpenid
} from '../../api/wx'
import {
	setOpenidStatus
} from '../../common/openId'
import {
	getUserIdentity
} from '../../common/utils'

export const wxKeyNames = 'RANDOM_CHARACTER_NEWS'

const useWx = defineStore(wxKeyNames, {
	state: () => {
		return {
			data: {},
		}
	},

	getters: {
		getOpenId: state => state.data.openId,
	},

	actions: {
		clear() {
			this.data = {}
		},
		// code 换取 openid
		getOpenidForCode(code) {
			// console.log('code ==============assasa=========> ', code);
			let that = this
			try {
				exchangeCodeForOpenid(code).then(res => {
					if (res.code === 1) {
						// 绑定openid
						const {
							role
						} = getUserIdentity()
						console.log('role ==========================> ', role);
						// 设置到指定的role对象中
						that.data[role] = res.data
					} else {
						// 获取openid失败 清空状态 重新获取
						setOpenidStatus(0)
					}
				})
			} catch (error) {
				console.log('errorerrorerrorerror ============> ', error);
				//TODO handle the exception
			}
		}
	},
	// 数据持久化
	unistorage: true // 开启后对 state 的数据读写都将持久化
})

export default useWx